import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url)
    const mobile = searchParams.get('mobile') || searchParams.get('phone')
    const deviceId = searchParams.get('device_id')
    const type = searchParams.get('type')
    const userId = searchParams.get('user_id')
    const startTime = searchParams.get('start_time')
    const endTime = searchParams.get('end_time')
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '20')
    const skip = (page - 1) * limit

    // 构建查询条件 - yh_logs表没有deleted_at字段
    const where: any = {}

    // 如果提供了用户ID，直接查询
    if (userId) {
      where.user_id = parseInt(userId)
    }
    // 如果提供了手机号，先查询用户
    else if (mobile) {
      const user = await prisma.smoke_user.findFirst({
        where: {
          mobile: mobile
        }
      })
      if (!user) {
        return NextResponse.json({
          success: false,
          message: '未找到该手机号对应的用户'
        }, { status: 404 })
      }
      where.user_id = user.id
    }

    // 设备ID过滤
    if (deviceId) {
      where.device_id = deviceId
    }

    // 类型过滤
    if (type) {
      where.type = type
    }

    // 时间范围过滤 - 根据timestamp字段筛选（毫秒时间戳）
    if (startTime || endTime) {
      where.timestamp = {}
      
      if (startTime) {
        // 将秒级时间戳转换为毫秒级时间戳进行比较
        const startTimestamp = BigInt(parseInt(startTime) * 1000)
        where.timestamp.gte = startTimestamp
      }
      
      if (endTime) {
        // 将秒级时间戳转换为毫秒级时间戳进行比较
        const endTimestamp = BigInt(parseInt(endTime) * 1000)
        where.timestamp.lte = endTimestamp
      }
    }

    // 查询健康日志
    const [logs, total] = await Promise.all([
      prisma.yh_logs.findMany({
        where,
        include: {
          user: {
            select: {
              id: true,
              mobile: true,
              name: true,
              avatar: true,
              gender: true,
              age: true,
              height: true,
              weight: true
            }
          }
        },
        orderBy: {
          created_at: 'desc'
        },
        skip,
        take: limit
      }),
      prisma.yh_logs.count({ where })
    ])

    // 格式化数据，处理BigInt类型
    const formattedLogs = logs.map((log: any) => {
      let parsedData = {}
      try {
        parsedData = JSON.parse(log.data || '{}')
      } catch (e) {
        parsedData = log.data || {}
      }

      return {
        id: Number(log.id),
        user_id: Number(log.user_id),
        type: log.type,
        device_id: log.device_id,
        data: parsedData,
        timestamp: log.timestamp.toString(),
        created_at: log.created_at.toString(),
        user: log.user ? {
          id: Number(log.user.id),
          mobile: log.user.mobile,
          name: log.user.name,
          avatar: log.user.avatar,
          gender: log.user.gender,
          age: log.user.age,
          height: log.user.height,
          weight: log.user.weight
        } : null
      }
    })

    return NextResponse.json({
      success: true,
      data: {
        logs: formattedLogs,
        pagination: {
          page,
          limit,
          total,
          pages: Math.ceil(total / limit)
        }
      },
      message: '健康数据获取成功'
    })
  } catch (error) {
    console.error('Health data query error:', error)
    return NextResponse.json({
      success: false,
      error: 'Database query failed',
      message: '健康数据查询失败'
    }, { status: 500 })
  }
}